import componentBehaviors from '../../../behaviors/component';
import { COMPONENT_OPTIONS } from '../../../constants/common';
import { getMaxNumber } from '../../../common/utils';

Component({
    behaviors: [componentBehaviors],
    options: {
        ...COMPONENT_OPTIONS,
    },
    properties: {
        show: {
            type: Boolean,
            value: false,
        },
        zIndex: {
            type: Number,
            value: 110,
        },
        productInfo: {
            type: Object,
            value: {},
        },
        selectSku: {
            type: Object,
            value: {},
        },
        count: {
            type: Number,
            value: 0,
        },
        // 数量可选
        canLimitCount: {
            type: Boolean,
            value: false,
        },
        limitCount: {
            type: Number,
            value: 0,
        },
    },
    observers: {
        'productInfo': function (val) {
            if (val && val.skus && val.skus.length) {
                const soldedQuantity = val.skus.reduce((s, c) => s + (c.soldedQuantity || 0), 0);
                const sku = val.skus[0];
                this.setData({
                    soldedQuantity,
                    maxCount: sku && sku.maximum != -1 ? (sku.maximum - sku.freezeQuantity) : getMaxNumber(),
                });
            }
        },
        'show, limitCount': function (show, limitCount) {
            show && limitCount && this.setData({ count: limitCount });
        },
    },
    /**
     * 组件的初始数据
     */
    data: {
        pictureIdx: 1,
        maxCount: getMaxNumber(),
        soldedQuantity: 0,
    },

    /**
     * 组件的方法列表
     */
    methods: {
        // 关闭
        onClose: function () {
            this.setData({
                show: false,
            });
            this.triggerEvent('close');
        },
        // 轮播图改变
        pictureChange: function (event) {
            const { current } = event.detail;
            this.setData({
                pictureIdx: current + 1,
            });
        },
        changeAction: function (e) {
            const { productInfo, count } = this.data;
            if (!count && e.detail && productInfo.productAttributeDefs && productInfo.productAttributeDefs.length) {
                productInfo.count = e.detail;
                this.triggerEvent('select', productInfo);
                this.setData({ count: '' });
                this.onClose();
            } else {
                this.setData({ count: e.detail });
            }
        },
        ensureAction: function () {
            const { productInfo, count, canLimitCount } = this.data;
            if (canLimitCount) {
                this.onClose();
                return;
            }
            productInfo.count = count;
            this.triggerEvent('ensure', productInfo);
            this.onClose();
        },
    }
})
